package com.adwin.addcoin.ui.main

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.adwin.addcoin.AddCoinApplication
import com.adwin.addcoin.R
import com.adwin.addcoin.base.BaseFragment
import com.adwin.addcoin.databinding.MainPersonalCenterFragmentBinding
import com.adwin.addcoin.repository.bean.HomeTaskBean
import com.adwin.addcoin.ui.adapter.TaskItemAdapter
import com.adwin.addcoin.ui.dialog.InvitationCodeDialog
import com.adwin.addcoin.ui.dialog.OpinionFeedbackDialog
import com.adwin.addcoin.ui.seetting.SettingActivity
import com.adwin.addcoin.ui.webview.WebViewActivity
import com.adwin.addcoin.utils.FlowKeyUtils
import com.adwin.addcoin.utils.PersonalMessageUtils
import com.adwin.addcoin.utils.getRePost
import com.adwin.addcoin.utils.installRepost
import com.bumptech.glide.Glide
import com.cashbird.app.infra.utils.FlowBus
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.MaterialHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.math.BigDecimal

class PersonalCenterFragment:BaseFragment<MainPersonalCenterFragmentBinding,PersonalCenterModel>
    (MainPersonalCenterFragmentBinding::inflate,PersonalCenterModel::class.java,false) {
    lateinit var binding: MainPersonalCenterFragmentBinding
    private var images = arrayListOf<String>("https://img2.baidu.com/it/u=1941383634,618713173&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500")
    private var pageNumber = 0
    private var tasks = ArrayList<HomeTaskBean>()
    private var inviteUrl = ""
    private var exchangeUrl = ""
    private var withdrawUrl = ""

    override fun onStart() {
        super.onStart()
        binding.personalCenterBanner.start()
    }

    override fun onStop() {
        super.onStop()
        binding.personalCenterBanner.stop()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding.personalCenterBanner.destroy()
    }

    override fun initFragment(
        binding: MainPersonalCenterFragmentBinding,
        savedInstanceState: Bundle?
    ) {
        this.binding = binding
        binding.tvPersonalCenterNickName.text = "Ethan yan"
        binding.personalCenterBanner.addBannerLifecycleObserver(this).setAdapter(object :
            BannerImageAdapter<String>(images){
            override fun onBindView(
                holder: BannerImageHolder?,
                data: String?,
                position: Int,
                size: Int
            ) {
                holder?.imageView?.let {
                    Glide.with(it.context).load(R.mipmap.add_coins_banner_icon).into(holder.imageView)
                    holder.imageView.setOnClickListener {
                        if (!TextUtils.isEmpty(inviteUrl)){
                            MainScope().launch (Dispatchers.IO){
                                val obj = JSONObject()
                                obj.put("addCoinUrl",inviteUrl)
                                context?.installRepost("centerInviteBannerClick",obj)
                            }
                            val intent = Intent(context, WebViewActivity::class.java)
                            intent.putExtra("url", inviteUrl)
                            startActivity(intent)
                        }
                    }
                }
            }
        })
        binding.tvPersonalWithdraw.setOnClickListener {
            val intent = Intent(context, WebViewActivity::class.java)
            if (AddCoinApplication.isCloak){
                if (TextUtils.isEmpty(exchangeUrl)) return@setOnClickListener
                MainScope().launch (Dispatchers.IO){
                    val obj = JSONObject()
                    obj.put("addCoinUrl",exchangeUrl)
                    context?.installRepost("centerExchangeClick",obj)
                }
                intent.putExtra("url",exchangeUrl)
            }else{
                if (TextUtils.isEmpty(withdrawUrl)) return@setOnClickListener
                MainScope().launch (Dispatchers.IO){
                    val obj = JSONObject()
                    obj.put("addCoinUrl",exchangeUrl)
                    context?.installRepost("centerWithdrawClick",obj)
                }
                intent.putExtra("url",withdrawUrl)
            }
            startActivity(intent)
        }
        myViewModel?.isLoad?.observe(this){
            binding.srlTaskRefresh.setEnableLoadMore(it)
        }
        FlowBus.with<String>(FlowKeyUtils.taskChange).register(lifecycle){
            onRefresh()
        }
        binding.srlTaskRefresh.setRefreshHeader(MaterialHeader(context))
        binding.srlTaskRefresh.setRefreshFooter(ClassicsFooter(context))
        binding.srlTaskRefresh.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener{
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                MainScope().launch (Dispatchers.IO){
                    context?.installRepost("centerTaskLoadMore")
                }
                onLoadMore()
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                MainScope().launch (Dispatchers.IO){
                    context?.installRepost("centerTaskRefresh")
                }
                onRefresh()
            }
        })
        binding.personalCenterBanner.start()
        myViewModel?.userInfoBean?.observe(this){
            if (it == null) return@observe
            binding.tvPersonalCenterNickName.text = it.userName
            Glide.with(binding.ivPersonalCenterUser).load(it.avatar).into(binding.ivPersonalCenterUser)
        }
        if (AddCoinApplication.isCloak){
            binding.tvPersonalCenterBonus.visibility = View.GONE
            binding.tvPersonalWithdraw.text = resources.getString(R.string.main_home_exchange_button)
        }else{
            binding.tvPersonalWithdraw.text = resources.getString(R.string.main_home_withdraw_button)
        }
        setOnClickListener()
        binding.rvTask.adapter = context?.let { TaskItemAdapter(tasks, it) }
        binding.rvTask.layoutManager = LinearLayoutManager(context,
            LinearLayoutManager.VERTICAL,false)
        myViewModel?.taskLists?.observe(this){taskLists ->
            tasks.clear()
            tasks.addAll(taskLists)
            binding.rvTask.adapter?.notifyDataSetChanged()
        }
        myViewModel?.isRefresh?.observe(this){
            if (!it){
                binding.srlTaskRefresh.finishRefresh()
                binding.srlTaskRefresh.finishLoadMore()
            }
        }
        PersonalMessageUtils.appDispositionBean.observe(this){appDisposition ->
            if (appDisposition != null){
                inviteUrl = appDisposition.INVITE
                exchangeUrl = appDisposition.EXCHANGE
                withdrawUrl = appDisposition.WITHDRAW
            }
        }

        PersonalMessageUtils.userCoinsBean.observe(this){
            it?.let {
                binding.tvPersonalCenterCoins.text = "${BigDecimal(it.coinNum).setScale(0)}"
                binding.tvPersonalCenterBonus.text = "= Rp${BigDecimal(it.conversionNum).setScale(2)}"
            }
        }
        onRefresh()
    }

    private fun onLoadMore(){
        pageNumber++
        myViewModel?.getTaskList(pageNumber)
    }

    private fun onRefresh(){
        pageNumber = 1
        myViewModel?.getUserInfo()
        myViewModel?.getTaskList(pageNumber)
    }

    private fun setOnClickListener(){
        binding.ivPersonalCenterFeedback.setOnClickListener {
            context?.let { it1 -> InvitationCodeDialog(it1).show() }
        }
        binding.ivPersonalCenterService.setOnClickListener {
            context?.let {
                OpinionFeedbackDialog(it).show()
                lifecycleScope.launch(Dispatchers.IO) {
                    val log = it.getRePost()
                    Log.d("checkIn", "logMessage:$log")
                }
            }

        }
        binding.ivPersonalCenterSetting.setOnClickListener {
            startActivity(Intent(context,SettingActivity::class.java))
        }
        PersonalMessageUtils.inviteDetailsBean?.observe(this){
            it?.let { inviteDetails ->
                if (!inviteDetails.inviteStatus){
                    binding.ivPersonalCenterFeedback.visibility = View.GONE
                }else{
                    binding.ivPersonalCenterFeedback.visibility = View.VISIBLE
                }
            }
        }
    }

    override fun onBackPressed(): Boolean = true
}